package com.dm0858.bianmin.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.databinding.FragmentMineBinding;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.mine.tools.ShapeUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.model.entity.BannerData;
import com.dm0858.bianmin.model.entity.Channel;
import com.dm0858.bianmin.model.response.BannerResponse;
import com.dm0858.bianmin.ui.activity.ArticleDetailActivity;
import com.dm0858.bianmin.ui.activity.LivingPaymentActivity;
import com.dm0858.bianmin.ui.activity.NormalListActivity;
import com.dm0858.bianmin.ui.activity.OtherNewsListActivity;
import com.dm0858.bianmin.ui.activity.SearchActivity;
import com.dm0858.bianmin.ui.activity.SearchModel;
import com.dm0858.bianmin.ui.activity.TravelBookingActivity;
import com.dm0858.bianmin.ui.activity.WebViewActivity;
import com.dm0858.bianmin.ui.activity.XiuXianActivity;
import com.dm0858.bianmin.ui.activity.YingshiActivity;
import com.dm0858.bianmin.ui.activity.ZiXunActivity;
import com.dm0858.bianmin.ui.base.BaseFragment;
import com.dm0858.bianmin.ui.presenter.BannerListPresenter;
import com.dm0858.bianmin.utils.CacheUtils;
import com.dm0858.bianmin.view.IBannerListView;
import com.dm0858.bianmin.view.IndexListViewFrame;
import com.google.gson.Gson;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.socks.library.KLog;
import com.sunfusheng.glideimageview.progress.GlideApp;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

/**
 * @author ChayChan
 * @description: 首页fragment
 * @date 2017/6/12  21:47
 */

public class HomeFragment extends BaseFragment<BannerListPresenter> implements IBannerListView, IndexListViewFrame.IXListViewListener {


    private FragmentMineBinding binding;

    /*@Bind(R.id.pb_loading)
    ProgressBar mPbLoading;

    @Bind(R.id.wv_content)
    WebView mWvContent;*/
//    @Bind(R.id.iv_back)
//    ImageView mIvBack;
//
//    @Bind(R.id.iv_member)
//    ImageView mmember;


    @Bind(R.id.rollPage)
    RollPagerView mRollViewPager;


    @Override
    protected BannerListPresenter createPresenter() {
        return new BannerListPresenter(this);
    }

    public static final String SECIONID = "AA";
    public static final String AREA = "AREA";
    public static final String LAT = "LAT";
    public static final String LNG = "LNG";


    @Bind(R.id.tv_location)
    TextView mtextview;

    @Bind(R.id.gridview)
    GridView mgridView;

    @Bind(R.id.videoplayer)
    JzvdStd jzVideoPlayerStandard;

    @Bind(R.id.trim_container)
    RelativeLayout trim_container;

    @Bind(R.id.liv_od_content)
    IndexListViewFrame liv_od_content;

    @Bind(R.id.edtTxt_addadd_search)
    EditText edtTxt_addadd_search;
    @Bind(R.id.oneBtn)
    Button oneBtn;
    @Bind(R.id.twoBtn)
    Button twoBtn;

    @Bind(R.id.img_jiaofei)
    ImageView imgJiaofei;
    @Bind(R.id.img_chuxing)
    ImageView imgChuxing;


    private static final int BAIDU_READ_PHONE_STATE = 100;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private List<String> imgs = new ArrayList<String>();

    private List<String> bannertype = new ArrayList<String>();
    private List<String> links = new ArrayList<String>();

    private List<Channel> mSelectedChannels = new ArrayList<>();
    private List<Channel> mUnSelectedChannels = new ArrayList<>();
    private List<NewsListFragment> mChannelFragments = new ArrayList<>();
    private Gson mGson = new Gson();

    MyAdapter myAdapter;

    private String data;
    private List<BannerResponse.DataBean.IndexnewsBean> madapter_data = new ArrayList<BannerResponse.DataBean.IndexnewsBean>();
    private List<String> groupkey = new ArrayList<String>();

    public String area = "0";
    public String lat = "0";
    public String lng = "0";
    public String sectionid = "";

//    //定义图标数组
//    private int[] imageRes = {
//            R.drawable.kaisuo,
//            R.drawable.peiche,
//            R.drawable.jiadian,
//            R.drawable.diannao,
//            R.drawable.ranju,
//            R.drawable.guandao,
//            R.drawable.shuidian,
//            R.drawable.juanmen,
//            R.drawable.banjia,
//            R.drawable.jiazheng,
//            R.drawable.zmf,
//            R.drawable.chongwu,
//            R.drawable.zhuangshi,
//            R.drawable.carweixiu,
//            R.drawable.paotui,
//            R.drawable.waimai,
//            R.drawable.jiaoyu,
//            R.drawable.baojing,
//            R.drawable.ershouche,
//            R.drawable.luntan,
//            R.drawable.dingpiao
//    };
//
//    //定义图标下方的名称数组
//    private String[] name = {
//            "开锁换锁",
//            "五金建材",
//            "家电维修",
//            "电脑维修",
//            "燃具维修",
//            "管道疏通",
//            "水电维修",
//            "卷门维修",
//            "搬家服务",
//            "家政服务",
//            "租房买房",
//            "宠物医疗",
//            "装饰维修",
//            "汽车快修",
//            "同城跑腿",
//            "生活资讯",
//            "教育培训",
//            "报警求助",
//            "二手汽车",
//            "民心论坛",
//            "手机订票"
//    };

    //定义图标数组
    private int[] imageRes = {
            R.drawable.weixiu,
            R.drawable.xinxi,
            R.drawable.bianmin,
            R.drawable.zixun,
            R.drawable.xiuxian,
            R.drawable.yinshi,
            R.drawable.qiuzhu,
            R.drawable.minxin
    };

    //定义图标下方的名称数组
    private String[] name = {
//            "生活维修",
            "生活服务",
            "生活信息",
            "生活便民",
            "生活资讯",
            "生活休闲",
            "生活影视",
            "遇险求助",
            "民心论坛"
    };

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home;
    }


    @Override
    public void initData() {


        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            startLocate();
        }


        imgJiaofei.setBackground(new ShapeUtils().corner(8).build());
        imgChuxing.setBackground(new ShapeUtils().corner(8).build());

        mtextview.setText(" 当前位置: 中国");


        mPresenter.getBanner();


        //生成动态数组，并且转入数据
        ArrayList<HashMap<String, Object>> listItemArrayList = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < imageRes.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImage", imageRes[i]);
            map.put("itemText", name[i]);
            listItemArrayList.add(map);
        }
        //生成适配器的ImageItem 与动态数组的元素相对应
        SimpleAdapter saImageItems = new SimpleAdapter(getActivity(),
                listItemArrayList,//数据来源
                R.layout.home_item,//item的XML

                //动态数组与ImageItem对应的子项
                new String[]{"itemImage", "itemText"},

                //ImageItem的XML文件里面的一个ImageView,TextView ID
                new int[]{R.id.img_shoukuan, R.id.txt_shoukuan});
        //添加并且显示
        mgridView.setAdapter(saImageItems);

        //添加消息处理
        mgridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getActivity(),name[position],Toast.LENGTH_LONG).show();

                if (position == 0 || position == 1 || position == 2) {
                    Intent intent = null;
                    intent = new Intent(mActivity, OtherNewsListActivity.class);

                    intent.putExtra(OtherNewsListActivity.STYPE, position);

                    startActivity(intent);
                    return;
                }

                if (position == 3) {
                    Intent intent = new Intent(mActivity, ZiXunActivity.class);
                    startActivity(intent);
                    return;
                }

                if (position == 4) {
                    Intent intent = new Intent(mActivity, XiuXianActivity.class);
                    startActivity(intent);
                    return;
                }

                if (position == 5) {
                    gotoKaka();
                    return;
                }

                if (position == 6) {
                    KLog.e("position=" + position);
                    Intent intent = null;
                    intent = new Intent(mActivity, NormalListActivity.class);

                    intent.putExtra(NormalListActivity.SECIONID, 17);
                    intent.putExtra(NormalListActivity.AREA, area);
                    intent.putExtra(NormalListActivity.LAT, lat);
                    intent.putExtra(NormalListActivity.LNG, lng);

                    startActivity(intent);
                    return;
                }
                if (position == 7) {
                    Intent intent = new Intent(mActivity, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.URL, "http://shequ.bmshfw.net/");
                    startActivity(intent);
                    return;
                }


            }
        });
        setListViewHeightBasedOnChildren(mgridView);
        //  mgridView.deferNotifyDataSetChanged();


        liv_od_content.setPullLoadEnable(true);
        liv_od_content.setXListViewListener(this);
        registerForContextMenu(liv_od_content);
        liv_od_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
                intent.putExtra(ArticleDetailActivity.id, madapter_data.get(arg2 - 1).id);
                startActivity(intent);

            }
        });


        initProgressDialog();

        oneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.show();
                String text = String.valueOf(edtTxt_addadd_search.getText());


                FinalHttp fh = new FinalHttp();
                fh.get("http://bmshfw.net/phpapi/info.php?func=searchAll&keyword=" + text + "&lat=" + lat + "&lng=" + lng, null, new AjaxCallBack() {


                    @Override
                    public void onSuccess(Object o) {
                        super.onSuccess(o);
                        progressDialog.dismiss();

                        Gson g = new Gson();
                        JSONObject json = null;
                        try {
                            json = new JSONObject(o.toString());
                            int code = 0;

                            code = json.getInt("status");
                            if (code == 1) {
                                SearchModel searchModel = g.fromJson(o.toString(), SearchModel.class);

                                Intent intent = new Intent(getActivity(), SearchActivity.class);
                                intent.putExtra("json", o.toString());
                                intent.putExtra("isWeb", false);
                                startActivity(intent);
                                Toast.makeText(getActivity(), "搜索成功",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(), "没有搜索结果",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "没有搜索结果",
                                    Toast.LENGTH_SHORT).show();
                        }


                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "搜索失败",
                                Toast.LENGTH_SHORT).show();

                    }
                });


            }
        });

        twoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = String.valueOf(edtTxt_addadd_search.getText());

                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("json", text);
                intent.putExtra("isWeb", true);
                startActivity(intent);


            }
        });
// 第三步，设置POI检索监听者；
        edtTxt_addadd_search.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
            }

            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            public void afterTextChanged(Editable arg0) {

            }

        });
        //
        SoftKeyboardUtil.observeSoftKeyboard(getActivity(), new SoftKeyboardUtil.OnSoftKeyboardChangeListener() {
            @Override
            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
                if (visible) {
                    //打开
                    oneBtn.setVisibility(View.VISIBLE);
                    twoBtn.setVisibility(View.VISIBLE);


                    // 获取gridview的布局参数

                    mtextview.setVisibility(View.GONE);
                } else {
                    oneBtn.setVisibility(View.GONE);
                    twoBtn.setVisibility(View.GONE);
                    edtTxt_addadd_search.clearFocus();
                    mtextview.setVisibility(View.VISIBLE);

                }
            }
        });


    }

    private ProgressDialog progressDialog;

    private void initProgressDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setIndeterminate(false);//循环滚动
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在搜索");
        progressDialog.setCancelable(false);//false不能取消显示，true可以取消显示

    }


    public void gotoKaka() {
        Intent intent = new Intent(mActivity, YingshiActivity.class);
        startActivity(intent);
        return;
    }

    @Override
    public void onRefresh() {
        if (madapter_data.size() > 0) {
            madapter_data.clear();
        }
        mPresenter.getBanner();
    }

    @Override
    public void onLoadMore() {
        onLoad();
    }

    @OnClick({R.id.img_chuxing, R.id.img_jiaofei, R.id.txt_techan, R.id.txt_yaodian, R.id.txt_sheying, R.id.txt_daijia, R.id.txt_zhusu, R.id.txt_meirong})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_chuxing:
                startActivity(new Intent(mActivity, TravelBookingActivity.class));
                sectionid = "";
                break;
            case R.id.img_jiaofei:
                startActivity(new Intent(mActivity, LivingPaymentActivity.class));
                sectionid = "";
                break;
            case R.id.txt_techan:
//                ToastUtils.showShort("本地特产");
                sectionid = "43";
                break;
            case R.id.txt_yaodian:
//                ToastUtils.showShort("药店医疗");
                sectionid = "39";
                break;
            case R.id.txt_sheying:
//                ToastUtils.showShort("婚庆摄影");
                sectionid = "41";
                break;
            case R.id.txt_daijia:
//                ToastUtils.showShort("平安代驾");
                sectionid = "13";
                break;
            case R.id.txt_zhusu:
//                ToastUtils.showShort("用餐住宿");
                sectionid = "40";
                break;
            case R.id.txt_meirong:
//                ToastUtils.showShort("美容健身");
                sectionid = "42";
                break;
        }
        if (!sectionid.equals("")) {
            intent = new Intent(mActivity, NormalListActivity.class);
            intent.putExtra(NormalListActivity.SECIONID, Integer.valueOf(sectionid));
            intent.putExtra(NormalListActivity.AREA, CacheUtils.getDriverCity(mActivity.getApplicationContext()));
            intent.putExtra(NormalListActivity.LAT, CacheUtils.getDriverLat(mActivity.getApplicationContext()));
            intent.putExtra(NormalListActivity.LNG, CacheUtils.getDriverLon(mActivity.getApplicationContext()));
            startActivity(intent);
        }
    }

    private class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            if (location.getCity() == null) {
                return;
            }
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            mtextview.setText(" 位置: " + street);
            area = district;
            lat = String.valueOf(location.getLatitude());
            lng = String.valueOf(location.getLongitude());
            CacheUtils.setDriverCity(getActivity().getApplicationContext(), area);
            CacheUtils.setTieDriverCity(getActivity().getApplicationContext(), city + "-" + district);

            CacheUtils.setDriverLat(getActivity().getApplicationContext(), lat);
            CacheUtils.setDriverLon(getActivity().getApplicationContext(), lng);
            KLog.e(area);
            //Toast toast=Toast.makeText(getContext(), "定位数据error code="+location.getLocType()+"lat="+location.getLatitude()+"&lng="+location.getLongitude(), Toast.LENGTH_LONG);

            // Toast toast=Toast.makeText(MainActivity.this, "定位数据error code="+location.getLocType()+"lat="+location.getLatitude()+"&lng="+location.getLongitude(), Toast.LENGTH_LONG);
            // showMyToast(toast, 20*1000);

            //    Toast.makeText(MainActivity.this, "定位数据lat="+location.getLatitude()+"&lng="+location.getLongitude(), Toast.LENGTH_SHORT).show();


        }
    }


    private void startLocate() {
        LogUtils.d("start");
        mLocationClient = new LocationClient(this.getContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 30 * 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        //  option.setOpenGps(true);//可选，默认false,设置是否使用gps
        //  option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
        //开启定位
//        showContacts();

        mLocationClient.start();
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    startLocate();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(this.getContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    public void showContacts() {
        if (ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this.getContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        } else {
            startLocate();
        }
    }

    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }

    private class TestNormalAdapter extends StaticPagerAdapter {
        private int[] imgs2 = {
                R.mipmap.a1,
                R.mipmap.a2,
        };


        @Override
        public View getView(ViewGroup container, int position) {


            if (bannertype.get(position).equals("1")) {


                jzVideoPlayerStandard.setUp(links.get(position)
                        , "", Jzvd.SCREEN_WINDOW_NORMAL);
                GlideApp.with(container.getContext()).load(imgs.get(position)).into(jzVideoPlayerStandard.thumbImageView);

                return jzVideoPlayerStandard;

            } else {
                ImageView view1 = new ImageView(container.getContext());

                //  view.setImageResource(imgs2[position]);
                view1.setScaleType(ImageView.ScaleType.CENTER_CROP);
                view1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                GlideApp.with(container.getContext()).load(imgs.get(position)).into(view1);
                return view1;
            }


        }


        @Override
        public int getCount() {
            return imgs.size();
        }
    }


    @Override
    public void initListener() {

    }


    @Override
    public void loadData() {

    }


    @Override
    public void onGetBannerListSuccess(BannerResponse bannerlist) {


        int length = madapter_data.size();
        if (length > 0) {
            madapter_data.clear();
        }
        madapter_data = bannerlist.data.indexnews;
        myAdapter = new MyAdapter();
        liv_od_content.setVisibility(View.VISIBLE);

        liv_od_content.setAdapter(myAdapter);
        setIndexNewsListViewHeight(liv_od_content, myAdapter, length);
        myAdapter.notifyDataSetChanged();
        onLoad();


        List<BannerData> banner1 = new ArrayList<>();
        banner1.addAll(bannerlist.data.banner);
        for (BannerData data : banner1) {
            imgs.add(data.address);
            KLog.e("ekod=" + data.address);

            bannertype.add(data.type);
            links.add(data.video);
        }

        //设置播放时间间隔
        mRollViewPager.setPlayDelay(15000);
        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置适配器
        mRollViewPager.setAdapter(new TestNormalAdapter());

        //设置指示器（顺序依次）
        //自定义指示器图片
        //设置圆点指示器颜色
        //设置文字指示器
        //隐藏指示器
        //mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
        mRollViewPager.setHintView(new ColorPointHintView(getContext(), Color.RED, Color.WHITE));
        //mRollViewPager.setHintView(new TextHintView(this));
        //mRollViewPager.setHintView(null);


    }

    /**
     * 正在加载时回调
     */
    private void onLoad() {
        liv_od_content.stopRefresh();
        liv_od_content.stopLoadMore();
    }


    @Override
    public void onError() {

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        if (mLocationClient.isStarted()) {
            mLocationClient.stop();
            LogUtils.d("stop");

        }
        super.onPause();
        jzVideoPlayerStandard.releaseAllVideos();
        trim_container.setVisibility(View.GONE);
        mRollViewPager.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        jzVideoPlayerStandard.releaseAllVideos();
        trim_container.setVisibility(View.GONE);
        mRollViewPager.setVisibility(View.VISIBLE);
    }


    public void cancleSelect() {
        //TODO something
        jzVideoPlayerStandard.releaseAllVideos();
    }

    static class ViewHolder {
        public TextView addexam_list_item_text;


    }

    public class MyAdapter extends BaseAdapter {

        ViewHolder holder = null;

        @Override
        public int getCount() {
            int count = madapter_data.size();
            return count;
        }

        @Override
        public Object getItem(int arg0) {
            int arg1 = arg0;
            return madapter_data.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            int arg1 = arg0;
            // TODO Auto-generated method stub
            return arg1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {

            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_text_news, null);
            ImageView fruitImage = (ImageView) convertView.findViewById(R.id.news_image);//获取该布局内的图片视图
            TextView fruitName = (TextView) convertView.findViewById(R.id.news_name);//获取该布局内的文本视图
//        fruitImage.setImageResource();//为图片视图设置图片资源

            RequestOptions options = new RequestOptions();

            options.placeholder(R.drawable.addnews);

            Glide.with(getContext()).load(madapter_data.get(position).address).apply(options).into(fruitImage);

            //     Glide.with(getContext()).load(madapter_data.get(position).address).into(fruitImage);
            fruitName.setText(madapter_data.get(position).title);//为文本视图设置文本内容

//            TextView tiametxt = (TextView) convertView.findViewById(R.id.news_time);//获取该布局内的文本视图
//            String timestr = DateUtils.dataOne(madapter_data.get(position).addtime);
//            tiametxt.setText(DateUtils.timedate(timestr));

            return convertView;


        }


    }

    public static void setIndexNewsListViewHeight(IndexListViewFrame listView, MyAdapter adapter, int count) {
        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {

            return;

        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

            View listItem = listAdapter.getView(i, null, listView);

            listItem.measure(0, 0); // 计算子项View 的宽高

            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        // listView.getDividerHeight()获取子项间分隔符占用的高度

        // params.height最后得到整个ListView完整显示需要的高度

        listView.setLayoutParams(params);
    }


    @Override
    public void onStop() {
        super.onStop();
    }
}

class SoftKeyboardUtil {
    public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int previousKeyboardHeight = -1;

            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom;
                int height = decorView.getHeight();
                int keyboardHeight = height - displayHeight;
                if (previousKeyboardHeight != keyboardHeight) {
                    boolean hide = (double) displayHeight / height > 0.8;
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide);
                }

                previousKeyboardHeight = height;

            }
        });
    }

    public interface OnSoftKeyboardChangeListener {
        void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
    }

}
